package cn.lzm.server.tcp;

import cn.lzm.server.Server;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetServer;

import java.nio.charset.StandardCharsets;

/**
 * @author lzm
 * @Date 2024/11/5
 * @description 基于tcp协议的服务器
 */
public class VertxTcpServerV2 implements Server {

    @Override
    public void start(int port) {
        Vertx vertx = Vertx.vertx();
        NetServer server = vertx.createNetServer();
        server.connectHandler(socket -> socket.handler(buffer -> {
            String msg = "hello, server! hello, server! hello, server! hello, server!";
            int messageLength = msg.getBytes().length;
            byte[] requestData = buffer.getBytes();
            if (requestData.length < messageLength) {
                System.out.println("半包，length = " + buffer.getBytes().length);
                return;
            }
            if (requestData.length > messageLength) {
                System.out.println("粘包，length = " + buffer.getBytes().length);
                return;
            }
            byte[] responseData = handRequest(requestData);
            socket.write(Buffer.buffer(responseData));
        }));

        server.listen(port, result -> {
            if (result.succeeded()) {
                System.out.println("Tcp server started on port " + port);
            } else {
                System.out.println("Failed to start Tcp server: " + result.cause());
            }
        });
    }

    private byte[] handRequest(byte[] requestData) {
        System.out.println("received from client: " + new String(requestData, StandardCharsets.UTF_8));
        return "hello, client!".getBytes();
    }

    public static void main(String[] args) {
        VertxTcpServerV2 tcpServer = new VertxTcpServerV2();
        tcpServer.start(8404);
    }

}
